#!/usr/bin/perl
#
#   prepare_cmudict.pl
#
#   Simple script to parse CMUdict and load everything into a 
#   JSON object as an associative array containing arrays as values.
#
#   ./prepare_cmudict.pl < cmudict.txt > cmudict.json
#

use strict;
use warnings;
use JSON qw(encode_json);

my $json = JSON->new->allow_nonref;
my (%dictionary, $index);

for (<>) {
    next if /^;;;/;
    $index = undef;
    my ($term, $arpa_string) = split "  ";
    if ($term =~ /^(.*) \( (\d+) \)/x) {
        $term = $1;
        $index = $2;
    }
    my (@arpa_array) = split ' ', $arpa_string;

    if ($index && $dictionary{$term}) {
        push @{ $dictionary{$term} }, \@arpa_array;
    }
    else {
        $dictionary{$term} = [ \@arpa_array ];
    }
}

print $json->encode(\%dictionary);

